//
//  申请退货Ctr.swift
//  Aiwei
//
//  Created by zhu xietong on 2018/1/9.
//  Copyright © 2018年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp
//import TPKeyboardAvoiding

//public typealias AfterApplyStep2 = 售后申请Ctr

public enum ApplyMode {
    case singe(goods:NSMutableDictionary,order:NSMutableDictionary)
    case order(order:NSMutableDictionary)
}

public class AfterApplyStep2: ListController {
    
    
    public var isCanSelectGoods = true
    
    public var mode = ApplyMode.order(order: NSMutableDictionary()){
        didSet{
            switch mode {
            case .order(order: let order):
                self.order = order
            case .singe(goods: _, order:let order):
                self.order = order
            }
        }
    }
    
    public var order = NSMutableDictionary()
    public var goods = NSMutableArray(){
        didSet{
            selectedGoodsIDs.removeAll()
            goods.list { (one:NSMutableDictionary, i) in
                one[FK.selected] = FK.YES
                selectedGoodsIDs.append(one["id",""])
            }
        }
    }
    
    public var serverType:SaleAfterType = SaleAfterType.returnMoney{
        didSet{
            title = "申请[XX]".replaceVars(values: serverType.name)
        }
    }
    
    public var maxReturnPrice:CGFloat = 0
    
    public var sections:TP.section{
        get{
            
            var goodsCellID = "goods"
            if !isCanSelectGoods{
                goodsCellID = "unselectGoods"
            }
            let sec:TP.section = [
                [
                    ["id":"__blank"],
                    ["cellID":goodsCellID,"goods":goods],
                    //                    [
                    //                        "title":"服务类型","cellID":"severType",
                    //                        FK.fields:[
                    //                            [
                    //                                FK.placeholder:"选择服务类型",
                    //                                FK.value:"1",
                    //                                FK.options:[["id":"0","name":"退款"],["id":"1","name":"退货"]],
                    //                                FK.field:StrField(id: "rtype", defaultV: nil, need: true, hiden: false, rule:
                    //                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请选择服务类型", err_msg: "检查服务类型"))
                    //                            ]
                    //                        ],
                    //                    ],
                    [
                        "title":"退款金额".loc,
                        "cellID":"price",
                        FK.fields:[
                            [
                                FK.placeholder:"请输入退款金额".loc,
                                FK.value:mo.detail["refundprice","0"],
                                FK.field:StrField(id: "price", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg:JoReg.price.rawValue, nil_msg: "请输入退款金额".loc, err_msg: "检查退款金额".loc)),
                                ],
                        ]
                    ],
                    ["id":"note","price":mo.detail["refundprice","0"]],
                    [
                        "cellID":"reason",
                        "title":"原因".loc,
                        FK.indicator:"<image>f_more_indicator",
                        FK.fields:[
                            [
                                "style":[
                                    "tiny":___shop.tint
                                ],
                                FK.placeholder:"选择原因".loc,
                                FK.options:FormTypes.types(names: [
                                    "物品与描述不符".loc,
                                    "物品寄送损坏".loc,
                                    "未收到物品".loc,
                                    "买家发货太慢".loc,
                                    "个人购买失误".loc
                                    ]),
                                FK.field:StrField(id: "reason", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请选择原因".loc, err_msg: "请选择原因".loc))
                            ]
                        ],
                        ],
                    [
                        "cellID":"description",
                        "title":"备注信息".loc,
                        "mark":"(选填)".loc,
                        FK.fields:[
                            [
                                FK.placeholder:"填写备注信息".loc,
                                FK.field:StrField(id: "content", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "检查备注信息".loc, err_msg: "请检备注信息".loc))
                            ]
                        ]
                    ],
                    [
                        "title":"上传凭证".loc,
                        "cellID":"files",
                        "mark":"",
                        FK.fields:[
                            [
                                FK.max_mum:"5",
                                FK.placeholder:"(\("支持jpg,png,jpeg最多5张，每张3M 以内".loc))",
                                FK.field:StrField(id: "images", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: ".{0,}", nil_msg: "请选择凭证图片".loc, err_msg: "请选择凭证图片".loc)),
                            ],
                        ]
                    ],
                ],
                [
                    ["id":"__blank40"],
                ]
            ]
            return sec
        }
    }
    
    public var selector:TP.selector{
        get{
            let sel:TP.selector = [
                "id<__blank>":BlankLine<line.px8>.self,
                "id<__blank40>":BlankLine<line.px40>.self,
                "id<note>":NoteCell.self,
                "cellID<severType>":SeverTypeCell.self,
                "cellID<description>":FTextAreaCell.self,
                "cellID<reason>":ReasonOptionCell.self,
                "cellID<goods>":GoodsCell<GoodsView>.self,
                "cellID<unselectGoods>":GoodsCell<GoodsView1>.self,
                "cellID<files>":MallForm.MGoodsUploadCell.self,
                "cellID<price>":PriceCell.self,
                ]
            return sel
        }
    }
    
    public var selectedGoodsIDs = [String]()
    
    public let bottomBar = SubmitBar()
    public override func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [bottomBar,[ee.L.B.R],"50"],
            [tableView,[bottomBar,ee.T,ee.B],[ee.L.R],[ee.T,TP.topHeight]],
        ]
        bottomBar.controller = self
    }
    
    public override func viewDidLoad() {
        //        title = "申请售后服务"
        tableView = TPKeyboardAvoidingTableView(frame: .zero, style: .plain)
        super.viewDidLoad()
        tableView.buildDynamicHeight(height: 60)
        tableView.backgroundColor =  ._tableBackground
        tableView.separatorStyle = .none
        tableView.tintColor = ___shop.tint
        
        FieldCell.name_width = 70
        FieldCell.padding_left = 21
        FieldCell.padding_right = 21
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        weak var wself = self
        bottomBar.nextAction = {
            wself?.beginSubmit()
        }
        
        //        print("==sss===|\(mo.model)")
        //        load(sections: sections, selector: selector)
        mo_request_send()
    }
    
    var orderID:String{
        get{
            var id = order["order.id",""]
            if id.len < 1
            {
                id = order["order",""]
            }
            return id
        }
    }
    
    public override func mo_request_send() {
        loadingV.loading()
        weak var wself = self
        
        var goodsID = ""
        switch self.mode {
        case .singe(goods: let goods, order: _):
            goodsID = goods["id",""]
        default:
            break
        }
        JoTask().post._surl(.退换货校验).log.params(["orderid":orderID,"goodsid":goodsID,"rtype":serverType.rawValue]).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                __post(notify: Goods.Notice.goodsOrderChange)
                if let info = obj as? NSMutableDictionary{
                    wself?.mo.detail = info
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "")
            }.run()
    }
    
    public override func mo_detail_reload() {
        maxReturnPrice = mo.detail[float:"refundprice",0]
        let _goods = mo.detail.any(nodes: "order.order.goods","order.goods", default: NSMutableArray())
        let __goods = NSMutableArray()
        _goods.list { (one:NSMutableDictionary, i) in
            if one["canrefund",false.tag] == true.tag
            {
                __goods.add(one)
            }
        }
        
        goods = __goods
        if goods.count < 1
        {
            mo_request_alert(msg:"不可发起[XX]申请".replaceVars(values: serverType.name), title: "", bt_title: "")
            return
        }
        
        
        tableView.load(sections: sections, selector: selector)
        tableView.reloadData()
        //        let price = mo.detail[float:"refundprice",0].price_display
    }
    
    public override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        if actionID == "updateTable"
        {
            tableView.beginUpdates()
            tableView.endUpdates()
        }
        if actionID == "selected_goods"
        {
            let anys = model.any(nodes: "selected_goods", default: NSMutableArray())
            self.selectedGoodsIDs.removeAll()
            
            anys.list { (str:String, i) in
                selectedGoodsIDs.append(str)
            }
        }
        //        print("+======|\(selectedGoodsIDs)")
    }
    
    
}

extension AfterApplyStep2{
    
    class PriceCell: FieldCell {
        
        class TextF: FTextField {
            
            let priceTag = UILabel()
            
            override func addLayoutRules() {
                self.eelay = [
                    [priceTag,[ee.L.Y]],
                    [valueT,[ee.T.L.B.R,[0,16,0,0,]]]
                ]
            }
            override func mo_model_reload() {
                valueFont = UIFont.systemFont(ofSize: 16)
                valueColor = .color(light: "#FC4D4D", dark: "#FC4D4D")
                priceTag.ui.font16.text(color: .color(light: "#FC4D4D", dark: "#FC4D4D")).text("¥")
                super.mo_model_reload()
            }
        }
        
        let textV = TextF()
        override func addLayoutRules() {
            super.addLayoutRules()
            
            //        let w = Int(FieldCell.name_width) + 20
            contentView.eelay = [
                [titleL,[ee.L.Y,[AppTheme.edge,0]],"40"],
                [textV,[ee.T.B,[0,0]],[titleL,ee.R,ee.L,8],[rightIcon,ee.L,ee.R,-8]],
            ]
            _ = titleL.ui.font13.text(color: ._foreground)
            textV.valueT.textAlignment = .left
            
        }
        
        override func mo_model_reload() {
            titleL.text = mo.model["title",""]
            textV.controller = self.content_controller
//            contentView.fillData(model: mo.model)
            
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
            {
                textV.mo.model = f
            }
            else
            {
                if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
                {
                    textV.mo.model = f
                }
            }
        }
        
    }
    
    public class SubmitBar: EeBottomBar {
        
        override public var contentHeight: CGFloat{
            get{
                return 60
            }
        }
        let sbBt = UIButton()
        
        var nextAction:()->Void = { }
        
        override public func addLayoutRules() {
            let line = UIView()
            contentView.eelay = [
                [line,[ee.T.L.R],"\(TP.separatorHeight)"],
                [sbBt,[ee.L.R.Y,[AppTheme.edge,-AppTheme.edge,0]],"36"],
            ]
            line.backgroundColor = UIColor.separator_color
            sbBt.ui.buttonColor(color: ._tint).ncolor(color: .white).font(size: 13).padding(insets: [6,12]).ntitle(title: "提交申请".loc).set(radius: 4, width: nil, color: nil)
            sbBt.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
        }
        
        @objc func confirmAction(){
            nextAction()
        }
    }
    
    
    //    class SubmitBar: EeBottomBar {
    //        let sbBt = UIButton()
    //
    //        var nextAction:()->Void = { }
    //        let priceL = UILabel()
    //
    //        override func addLayoutRules() {
    //            let line = UIView()
    //            contentView.eelay = [
    //                [line,[ee.T.L.R],"0.4"],
    //                [sbBt,[ee.R.Y,[-AppTheme.edge,0]]],
    //                [priceL,[sbBt,ee.Y],[ee.L,AppTheme.edge]]
    //            ]
    //            line.backgroundColor = UIColor.separator_color
    //            sbBt.ui.buttonColor(hex: UIColor.main_hex).ncolor(hex: "#fff").font(size: 13).padding(insets: [6,12]).ntitle(title: "提交申请").set(radius: 4, width: nil, color: nil)
    //            sbBt.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
    //        }
    //
    //        @objc func confirmAction(){
    //            nextAction()
    //        }
    //    }
    
    class NoteCell: JoTableCell {
        let infoL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [infoL,[ee.T.L.B.R,[8,AppTheme.edge,-16,-AppTheme.edge]]]
            ]
            contentView.backgroundColor = UIColor._tableBackground
            infoL.numberOfLines = 0
        }
        override func mo_model_reload() {
            
            let price = mo.model[float:"price",0]
            let str = "当前商品最高可退金额为[XX]¥，建议请先与买家协商退款金额".replaceVars(values: price.price_display)
            infoL.attributedText = str.ui.font12.color(color: ._weak).lineSpace(5).astring
            
        }
    }
    
    class BaseCell:JoTableCell{
        let titleL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.R,[16,AppTheme.edge,-AppTheme.edge]]],
            ]
            _ = titleL.ui.font14.text(color: ._foreground)
        }
        override func mo_model_reload() {
            titleL.text = mo.model["title",""]
        }
        
    }
    
    class SeverTypeCell: EeFieldCell {
        
        var field = TagsOptionField<RadioKit>()
        override func addLayoutRules() {
            titleL.ui.font15.text(color: ._foreground).node("title")
            titleL.font = FieldView.valueStyle.font
            titleL.textColor = FieldView.valueStyle.color
            
            
            let w = Int(FieldCell.name_width)
            let t = Int(FieldCell.padding_top)
            let b = Int(FieldCell.padding_bottom)
            
            let l = Int(FieldCell.padding_left)
            //        let r = Int(FieldCell.padding_right)
            
            
            contentView.eelay = [
                [titleL,[ee.T.L.B,[t,l,-b]],"21",.<w],
                [field,[titleL,ee.R,ee.L,14],[requiredMark,ee.L,ee.R,-10],[ee.Y]],
                [requiredMark,[titleL,ee.Y,3],[titleL,ee.R,ee.L,2]],
                [__line,[ee.L.B.R,[0,0.0]],"0.5"]
            ]
            self.indicator = .none
            
            __line.backgroundColor = FieldCell.separator_color
            titleL.setContentConstrainToHighLever()
            requiredMark.ui.font18.text("*").text(color: .clear)
            rightIcon.ui.font(size: 13).ncolor(hex: "#aaa")
        }
        
        
        override func mo_model_reload() {
            
            super.mo_model_reload()
            titleL.text = mo.model["title",""]

            field.controller = self.content_controller
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
            {
                field.mo.model = f
            }
            else
            {
                if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
                {
                    field.mo.model = f
                }
            }
        }
        
    }
    
    class ReasonOptionCell: FieldCell {
        
        let selector = FOneSelectorFeild()
        override func addLayoutRules() {
            super.addLayoutRules()
            contentView.eelay = [
                [titleL,FieldCell.name_width.+1000],
                [selector,[ee.T.B],[titleL,ee.R,ee.L,8],[rightIcon,ee.L,ee.R,-8]],
            ]
            selector.valueL.textAlignment = .right
        }
        
        
        var selectorModel:NSMutableDictionary{
            get{
                return selector.mo.model
            }
        }
        
        override func mo_model_reload() {
            titleL.text = mo.model["title",""]
            selector.controller = self.content_controller
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
            {
                selector.mo.model = f
            }
        }
    }
    
    //
    //    class QuestionCell:BaseCell{
    //        override func addLayoutRules() {
    //            super.addLayoutRules()
    //            _ = selector.valueL.ui.center
    //            contentView.eelay = [
    //                [selector,[titleL,ee.B.L,ee.T.L,[12,0]],[ee.R,-AppTheme.edge],[ee.B,-10]],
    //            ]
    //            selector.valueL.textAlignment = .center
    //            selector.bsui.background(color: UIColor.table_bg_color).set(radius: 0, width: 1, color: __cl_border)
    //            let tap = UITapGestureRecognizer(target: self, action: #selector(openSelector))
    //            contentView.addGestureRecognizer(tap)
    //        }
    //        let selector = FOneSelectorFeild()
    //
    //        @objc func openSelector() {
    //            selector.selecctAction()
    //        }
    //
    //        override func mo_model_reload() {
    //
    //            super.mo_model_reload()
    //            selector.controller = self.content_controller
    //            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
    //            {
    //                selector.mo.model = f
    //            }
    //        }
    //
    //
    //
    //    }
    //
    class DescCell: BaseCell {
        var field = TextAreaField()
        override func addLayoutRules() {
            super.addLayoutRules()
            contentView.eelay = [
                [field,[titleL,ee.B,ee.T,12],[ee.B,-30],"70",[ee.L.R,[AppTheme.edge,-AppTheme.edge]]],
            ]
            field.bsui.background(color:  UIColor.table_bg_color).set(radius: 0, width: 1, color: UIColor(shex: AppTheme.border_hex))
        }
        
        override func mo_model_reload() {
            super.mo_model_reload()
            if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
            {
                field.mo.model = f
            }
            else
            {
                if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
                {
                    field.mo.model = f
                }
            }
            field.valueT.bsui.background(color:  UIColor._cellBackground)
        }
        
    }
    
    
    class GoodsView1:GoodsView{
        override func willLayoutRules() {
            eelay = [
                [goodsV,[ee.T.L.B.R]]
            ]
        }
    }
    
    class GoodsView: RuleCell {
        let imgV = UIImageView()
        let titleL = UILabel()
        let tagsL = UILabel()
        let priceL = UILabel()
        let numL = UILabel()
        
        let selectedBt = UIButton()
        let goodsV = UIView()
        
        let statusL = UILabel()
        let disableLayer = UIView()
        
        func willLayoutRules() {
            eelay = [
                [selectedBt,"20",20,[ee.L.Y,[10,0]]],
                [goodsV,[ee.T.B.R],[selectedBt,ee.R,ee.L,10]],
            ]
            //            addSubview(disableLayer)
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            //            disableLayer.frame = self.bounds
        }
        
        var able:Bool{
            get{
                return mo.model["canrefund",false.tag] == true.tag
            }
        }
        
        override func addLayoutRules() {
            
            willLayoutRules()
            selectedBt.ui.simage(UIImage(named: "radio_check_s")).nimage(UIImage(named: "radio_check_n"))
            goodsV.eelay = [
                [imgV,[ee.Y.L,[0,0]],"64",64],
                [titleL,[imgV,ee.R,ee.L,8],[imgV,ee.T,4],[ee.R,-80]],
                [tagsL,[imgV,ee.R,ee.L,8],[imgV,ee.B,-4],[ee.R,-60]],
                [priceL,[ee.R],[titleL,ee.Y]],
                [numL,[ee.R],[tagsL,ee.Y]],
                //            [__line,[ee.L.B.R,[0,0.0]],"0.5"]
            ]
            //        __line.backgroundColor = FieldCell.separator_color
            
            imgV.img_url = __goods.one_str
            titleL.ui.font12.text(color: ._foreground).text(__goodsNames.one_str)
            tagsL.ui.font12.text(color: ._weak).text("颜色：黑")
            priceL.ui.font12.text(color: ._foreground).right.text("¥ 120")
            numL.ui.font12.text(color: ._weak).right.text("X1")
            selectedBt.addTarget(self, action: #selector(pressed), for: UIControl.Event.touchUpInside)
            
        }
        
        override func pressed() {
            if mo.model[FK.selected,FK.NO] == FK.YES
            {
                mo.model[FK.selected] = FK.NO
            }
            else{
                mo.model[FK.selected] = FK.YES
            }
            selectedBt.isSelected = isSelectedGoods
            self.delegate?.active(onwer: self, actionID: "toggle", data: mo.model)
            
        }
        
        override func mo_model_reload() {
            
            self.isUserInteractionEnabled = true
            imgV.img_url = mo.model["thumb",""]
            titleL.text = mo.model["title",""]
            tagsL.text = mo.model["optiontitle",""]
            priceL.text = "¥ " + mo.model[float:"marketprice",0].price_display
            numL.text = "X " + mo.model["total","1"]
            selectedBt.isSelected = isSelectedGoods
            
            //            if !able
            //            {
            //                addSubview(disableLayer)
            //                disableLayer.frame = self.bounds
            //                mo.model[FK.selected] = FK.NO
            //                selectedBt.isSelected = isSelectedGoods
            //            }
            //            else{
            //                disableLayer.removeFromSuperview()
            //            }
            //
            
            
        }
        
        var isSelectedGoods: Bool{
            get{
                return (mo.model[FK.selected,FK.NO] == FK.YES)
            }
        }
        @objc func selectToggle() {
            if mo.model[FK.selected,FK.NO] == FK.YES
            {
                mo.model[FK.selected] = FK.YES
            }
            else{
                mo.model[FK.selected] = FK.NO
            }
            selectedBt.isSelected = isSelectedGoods
        }
    }
    
    
    
    class GoodsCell<Kit:RuleCell>: JoTableCell {
        
        
        let goodsV = GoodsListView<Kit>()
        
        override func addLayoutRules() {
            
            contentView.eelay = [
                [goodsV,[ee.T.L.B.R,[10,AppTheme.edge,-10,-AppTheme.edge]]],
                [__line,[ee.L.B.R],"\(TP.separatorHeight)"]
            ]
            __line.backgroundColor = ._separator
            goodsV.listV.options_node = "goods"
            goodsV.listV.item_height = 74
            goodsV.listV.space = (0,8)
            
            goodsV.isUserInteractionEnabled = true
            goodsV.listV.touchAction = {[weak self] owner,ID,data in
                self?.markSelect(obj: data)
            }
        }
        
        func markSelect(obj:NSMutableDictionary) {
            let goods = mo.model.any(nodes: "goods", default: NSMutableArray())
            goods.list { (dict:NSMutableDictionary, i) in
                if obj["id","xx"] == dict["id","aa"]
                {
                    dict[FK.selected] = obj[FK.selected,FK.NO]
                }
            }
            
            var ids = [String]()
            goods.list { (dict:NSMutableDictionary, i) in
                if dict[FK.selected,FK.NO] == FK.YES
                {
                    ids.append(dict["id",""])
                }
            }
            
            mo.model["selected_goods"] = ids.mutable_array
            active(ID: "selected_goods", object: mo.model)
        }
        
        override func mo_model_reload() {
            goodsV.mo.model = mo.model
        }
        
        
    }
    
}

